#include "game_id_generator.h"

/* | 48bit: time stamp | 8bit server id | 8bit sequence id | */
uint64_t game_id_generator::generate() {
    auto now = std::chrono::system_clock::now();
    uint64_t timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
        now.time_since_epoch()).count();
    
    std::lock_guard<std::mutex> lock(mutex_);
    if (timestamp == last_timestamp_) {
        sequence_ = (sequence_ + 1) & 0xFFF;
        if (sequence_ == 0) {
            // 等待下一毫秒
            auto last_time_ = now;
            while (now <= last_time_) {
                now = std::chrono::system_clock::now();
            }
        }
    } else {
        sequence_ = 0;
    }
    
    last_timestamp_ = timestamp;
    return ((timestamp & 0xFFFFFFFFFFFF) << 16) |
            ((server_id_ & 0xFF) << 8) |
            (sequence_ & 0xFF);
}